<?php
declare(strict_types=1);

namespace app\controller\api;

use app\BaseController;
use app\model\{Order, Kuaidi100Order};
use think\facade\{Db, Log, Cache};
use think\Request;

class Kuaidi100Controller extends BaseController
{
    /**
     * 快递100订单状态回调
     */
    public function orderNotify(Request $request)
    {
        try {
            $data = $request->post();
            Log::info('快递100订单回调:', $data);
            
            // 验证签名
            if (!$this->verifySign($data)) {
                throw new \Exception('签名验证失败');
            }
            
            // 查找订单
            $order = Kuaidi100Order::where('task_id', $data['taskId'])->find();
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            
            Db::startTrans();
            try {
                // 更新快递100订单状态
                $order->save([
                    'status' => $data['status'],
                    'last_weight' => $data['lastWeight'] ?? '',
                    'courier_name' => $data['courierName'] ?? '',
                    'courier_mobile' => $data['courierMobile'] ?? '',
                    'update_time' => date('Y-m-d H:i:s')
                ]);
                
                // 更新系统订单状态
                $this->updateOrderStatus($order, $data);
                
                Db::commit();
                return json(['result' => true, 'returnCode' => '200', 'message' => '成功']);
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            Log::error('快递100订单回调处理失败: ' . $e->getMessage());
            return json(['result' => false, 'returnCode' => '500', 'message' => $e->getMessage()]);
        }
    }
    
    /**
     * 快递100物流轨迹回调
     */
    public function logisticsNotify(Request $request)
    {
        try {
            $data = $request->post();
            Log::info('快递100物流回调:', $data);
            
            // 验证签名
            if (!$this->verifySign($data)) {
                throw new \Exception('签名验证失败');
            }
            
            // 缓存物流信息
            $cacheKey = "logistics:{$data['kuaidicom']}:{$data['kuaidinum']}";
            Cache::set($cacheKey, $data['data'], 600);
            
            // 更新订单物流状态
            if ($data['status'] == '3') { // 已签收
                Order::where('express_no', $data['kuaidinum'])
                    ->where('order_status', '<>', 13)
                    ->update([
                        'order_status' => 13,
                        'sign_time' => date('Y-m-d H:i:s')
                    ]);
            }
            
            return json(['result' => true, 'returnCode' => '200', 'message' => '成功']);
        } catch (\Exception $e) {
            Log::error('快递100物流回调处理失败: ' . $e->getMessage());
            return json(['result' => false, 'returnCode' => '500', 'message' => $e->getMessage()]);
        }
    }
    
    /**
     * 更新订单状态
     */
    protected function updateOrderStatus($kuaidi100Order, $data)
    {
        $order = Order::where('order_no', $kuaidi100Order->order_id)->find();
        if (!$order) {
            return;
        }
        
        $statusMap = [
            '1' => 2,    // 已接单
            '2' => 3,    // 收件中
            '10' => 4,   // 已取件
            '13' => 13,  // 已签收
            '14' => 14,  // 异常签收
            '99' => 99   // 订单已取消
        ];
        
        if (isset($statusMap[$data['status']])) {
            $order->save([
                'order_status' => $statusMap[$data['status']],
                'express_no' => $data['kuaidinum'] ?? '',
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            // 如果已签收，记录签收时间
            if ($data['status'] == '13') {
                $order->save(['sign_time' => date('Y-m-d H:i:s')]);
            }
        }
    }
    
    /**
     * 验证签名
     */
    protected function verifySign($data)
    {
        $key = config('kuaidi100.key');
        $param = json_encode($data['param']);
        $sign = md5($param . $key . $data['param']['com'] . $data['param']['num']);
        return $sign === $data['sign'];
    }
} 